package com.bluelinelabs.logansquare;

import com.bluelinelabs.logansquare.data.ListAdapter;
import com.bluelinelabs.logansquare.model.Response;
import com.bluelinelabs.logansquare.model.User;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * 入口页面
 */
public class MainAbility extends Ability {
    private static final int ITERATIONS = 20;

    private List<String> mJsonStringsToParse;
    private List<Response> mResponsesToSerialize;
    private Text header;
    ListContainer listContainer;
    ListAdapter adapter;
    List<User> datas;
    Text txtSerializer;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        header = (Text) findComponentById(ResourceTable.Id_text_head);

        mJsonStringsToParse = readJsonFromFile();

        mResponsesToSerialize = getResponsesToParse();
        datas = new ArrayList<>();

        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list);
        adapter = new ListAdapter(this, datas);
        listContainer.setItemProvider(adapter);

        txtSerializer = (Text) findComponentById(ResourceTable.Id_serializer);

        Button buttonone = (Button) findComponentById(ResourceTable.Id_btn_one);
        buttonone.setClickedListener(
                new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        performParseTests();
                    }
                });

        Button buttonTow = (Button) findComponentById(ResourceTable.Id_btn_tow);
        buttonTow.setClickedListener(
                new Component.ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        performSerializeTests();
                    }
                });
    }

    private void performParseTests() {
        listContainer.setVisibility(Component.VISIBLE);
        txtSerializer.setVisibility(Component.HIDE);
        adapter.setData(mResponsesToSerialize.get(0).users);
    }

    //
    private void performSerializeTests() {
        listContainer.setVisibility(Component.HIDE);
        txtSerializer.setVisibility(Component.VISIBLE);

        Response response = mResponsesToSerialize.get(0);
        String resStr = null;
        try {
            resStr = LoganSquare.serialize(response);
        } catch (IOException e) {
            resStr = "fail";
        }

        txtSerializer.setText(resStr);
    }

    private List<Response> getResponsesToParse() {
        List<Response> responses = new ArrayList<>();

        try {
            for (String jsonString : mJsonStringsToParse) {
                Response response = LoganSquare.parse(jsonString, Response.class);

                responses.add(response);
            }
        } catch (Exception e) {
            Toast("解析失败");
        }

        return responses;
    }

    private List<String> readJsonFromFile() {
        List<String> strings = new ArrayList<>();

        strings.add(getOriginalFundData(this, "largesample.json"));
        strings.add(getOriginalFundData(this, "mediumsample.json"));
        strings.add(getOriginalFundData(this, "smallsample.json"));
        strings.add(getOriginalFundData(this, "tinysample.json"));

        return strings;
    }

    /**
     * 获取去最原始的数据信息
     * @param context c
     * @param name  name
     * @return json data
     */
    public String getOriginalFundData(Context context, String name) {
        InputStream input = null;
        try {
            // json文件名称
            RawFileEntry entry = context.getResourceManager().getRawFileEntry("resources/rawfile/" + name);
            input = entry.openRawFile();

            String json = convertStreamToString(input);
            return json;
        } catch (Exception e) {
            Toast("获取Json文件失败");
        };
        return null;
    }

    /**
     * input 流转换为字符串
     *
     * @param is is
     * @return String
     */
    private String convertStreamToString(InputStream is) {
        String s = null;
        try {
            // 格式转换
            Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A");
            if (scanner.hasNext()) {
                s = scanner.next();
            }
            is.close();
        } catch (IOException e) {
            Toast("转换失败");
        }
        return s;
    }

    /**
     * Toast
     * @param string string
     */
    public void Toast(String string) {
        new ToastDialog(this).setContentText(string).setDuration(3000).show();
    }
}
